package top.zerozoo.learn.grade.dao.impl;

import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import top.zerozoo.learn.grade.dao.MajorDao;
import top.zerozoo.learn.grade.entity.Major;
import top.zerozoo.learn.grade.util.JdbcUtils;

import java.util.List;

public class MajorDaoImpl implements MajorDao {

    private JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());

    @Override
    public int count() {
        final String sql = "select count(*) from major";
        return template.queryForObject(sql,Integer.class);
    }

    @Override
    public List<Major> findAll() {
        final String sql = "select * from major";
        List<Major> result = template.query(sql,new BeanPropertyRowMapper<>(Major.class));
        return result;
    }

    @Override
    public Major findById(int id) {
        final String sql = "select * from major where id = ?";
        Major result;
        try{
            result = template.queryForObject(sql,new BeanPropertyRowMapper<>(Major.class),id);
        }catch (IncorrectResultSizeDataAccessException ex){
            return null;
        }
        return result;
    }


    @Override
    public int insert(Major major) {
        final String sql = "insert into major(name) values(?)";
        return template.update(sql, major.getName());
    }

    @Override
    public int update(Major major) {
        final String sql = "update major set name = ? where id = ?";
        return template.update(sql, major.getName(), major.getId());
    }

    @Override
    public int deleteById(int id) {
        final String sql = "delete from major where id = ?";
        return template.update(sql,id);
    }
}
